package com.juejin.www.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


/**
 * MD5加密方法
 * @author Jacky
 */
public final class MD5Util {
    public static String encrypt(String strSrc) {
        try {
            char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                    '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            byte[] bytes = strSrc.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            bytes = md.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (byte b : bytes) {
                chars[k++] = hexChars[b >>> 4 & 0xf];
                chars[k++] = hexChars[b & 0xf];
            }
            return new String(chars);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("MD5加密出错！！+" + e);
        }
    }

    public static String generateSalt(int length) {
        // 创建一个SecureRandom实例
        SecureRandom random = new SecureRandom();

        // 创建一个字节数组来存储随机生成的盐值
        byte[] salt = new byte[length];

        // 填充字节数组以生成盐值
        random.nextBytes(salt);

        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder(2 * salt.length);
        for (byte b : salt) {
            String hex = Integer.toHexString(0xff & b);
            if(hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        // 返回生成的盐值
        return hexString.toString();
    }
}
